package com.wanjia.estate.filter;

import cn.hutool.core.util.StrUtil;
import com.wanjia.estate.utils.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

@Component
@Slf4j
public class EstateFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {

        if (servletRequest instanceof HttpServletRequest) {
            log.debug("working");
            HttpServletRequest request = (HttpServletRequest) servletRequest;

            // 加载全局参数
            loadProperties(request);

            // 请求处理与全局参数清空
            try {
                filterChain.doFilter(servletRequest, servletResponse);
            } finally {
                clearProperties();
                log.debug("clear all and over");
            }
            return;
        }

        // 未知请求类型，不予处理
        log.debug("Unknown request type, EstateFilter not works");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private void clearProperties() {
        ThreadUtil.removeAll();
    }

    private void loadProperties(HttpServletRequest request) {
        // 加载受理编号
        String slbh = request.getHeader("slbh");
        if (StrUtil.isNotEmpty(slbh)) {
            ThreadUtil.setSlbh(slbh);
            log.debug("load slbh: {}", slbh);
        }

        // 加载当前请求时间
        Date now = new Date();
        ThreadUtil.setNow(now);
        log.debug("load now: {}", now);
    }
}
